package utils;

import java.util.concurrent.TimeUnit;

import rx.Observable;
import rx.Scheduler;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action0;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

public class RxUtils {

    private RxUtils() {
        throw new UnsupportedOperationException("u can't fuck me...");
    }

    /**
     * 主线程
     */
    public static Subscription runOnUiThread(Action1<Long> onNext) {
        return runOnUiThread(0, onNext);
    }

    public static Subscription runOnUiThread(Action1<Long> onNext, Action1<? super Throwable> onError) {
        return runOnUiThread(0, onNext, onError);
    }

    public static Subscription runOnUiThread(long delay, Action1<Long> onNext) {
        return runOnUiThread(delay, onNext, null);
    }

    public static Subscription runOnUiThread(long delay, Action1<Long> onNext, Action1<? super Throwable> onError) {
        return runOn(delay, AndroidSchedulers.mainThread(), onNext, onError);
    }
    /**
     * @param delay     延迟（时间单位：秒）
     * @param scheduler 调度器
     * @param onNext    要执行的动作
     * @param onError   错误处理
     */
    public static Subscription runOn(long delay, Scheduler scheduler, final Action1<Long> onNext, final Action1<? super Throwable> onError) {
        return Observable.timer(delay, TimeUnit.SECONDS).observeOn(scheduler).subscribe(new Action1<Long>() {
            @Override
            public void call(Long aLong) {
                if (onNext != null) {
                    onNext.call(aLong);
                }
            }
        }, new Action1<Throwable>() {
            @Override
            public void call(Throwable throwable) {
                if (onError != null) {
                    onError.call(throwable);
                }
            }
        });
    }
    public static void runOnNewThread(Action0 onCompleted) {
        runOnNewThread(0, onCompleted);
    }

    public static void runOnNewThread(long delay, Action0 onCompleted) {
        runOn(Schedulers.newThread(), onCompleted);
    }

    public static void runOnIoThread(Action0 onCompleted) {
        runOnIoThread(0, onCompleted);
    }

    public static void runOnIoThread(long delay, Action0 onCompleted) {
        runOn(delay, Schedulers.io(), onCompleted);
    }

    public static void runOnComputation(Action0 action0) {
        runOn(0,Schedulers.computation(),action0);
    }

    public static void runOn(Scheduler scheduler, Action0 onCompleted) {
        runOn(0, scheduler, onCompleted);
    }

//    public static void runOnComputation(Action0 onCompleted) {
//        runOn(0, Schedulers.computation(), onCompleted);
//    }

    public static void runOn(long delay, Scheduler scheduler, Action0 onCompleted) {
        Observable.timer(delay, TimeUnit.SECONDS).observeOn(scheduler).doOnCompleted(onCompleted).subscribe();
    }


}
